<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Sms;
use app\common\model\User;
use think\Validate;

/**
 * 登录接口
 */
class Auth extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 检测手机号码
     * @Explain :
     * @Date : 2020/11/2 15:06
     * @Author : 河南邦耀网络科技有限公司
     */

    public function checkMobile(){
        header("access-control-allow-headers:*");
        header("access-control-allow-methods:*");
        header("access-control-allow-origin:*");
        $mobile = $this->request->request('mobile');
        $userinfo = User::getByMobile($mobile);
        if(empty($userinfo)){
            $this->success('可以注册',1);
        }
        $this->success('号码已注册',0);
    }
    /**
     * 会员登录
     * @ApiMethod   (POST)
     * @param string $mobile  手机号
     * @param string $code 验证码
     */
    public function login()
    {
        header("access-control-allow-headers:*");
        header("access-control-allow-methods:*");
        header("access-control-allow-origin:*");
        $mobile = $this->request->request('mobile');
        $code = $this->request->request('code');
        if (!$mobile || !$code) {
            $this->error(__('Invalid parameters'));
        }
        $mobileInfo = explode(",",\think\config::get("site.whitemobile"));
        if(!@in_array($mobile,$mobileInfo)) {
            $ret = Sms::check($mobile, $code, 'login');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
        }
        $ret = $this->auth->login($mobile);
        if ($ret) {
            $data = [
                'userinfo' => $this->auth->getUserinfo(),
                "titleInfo"=> $this->auth->getTitleInfo(),
            ];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }
    /**
     * 微信登陆
     * @ApiMethod   (POST)
     * @param string $code  微信code
     * @ApiReturn   (
    {
    "code": 1,
    "msg": "登录成功",
    "time": "1575515739",
    "data": {
    "userinfo": {
    "id": 5,
    "mobile": "18749320615",
    "username": "18749320615",
    "score": 0,
    "nickname": "18749320615",
    "avatar": "",
    "token": "8c2cea68-755d-4ecd-a859-18248ca41540",
    "user_id": 5,
    "createtime": 1575515739,
    "expiretime": 1578107739,
    "expires_in": 2592000
    }
    })
     */
    public function wechatLogin()
    {
        $code = $this->request->request("code");
        if(empty($code)){
            $this->error(__('Code parameters'));
        }
        $result = $this->auth->getWechatUserInfo($code);
        if($result == false){
            $this->error(__('UserInfo parameters'));
        }
        $loginret = $this->auth->wechatConnect($result);
        if ($loginret == false) {
            $this->error(__('Logged in error'));
        }
        $userInfo = $this->auth->getUser();
        if(empty($userInfo)){
            $data = [
                'wechat'  => base64_encode(json_encode($result)),
                "userinfo"  => array(
                    "id"=>0,
                    "bind"=>1,
                ),
            ];
            $this->success(__('Wechat binding information return'), $data);
        }else{
            $data = [
                'userinfo'  => $this->auth->getUserinfo(),
                "titleInfo"=>$this->auth->getTitleInfo(),
            ];
            $this->success(__('Logged in successful'), $data);
        }
    }
    /**
     * 注册会员
     * @ApiMethod   (POST)
     * @param string $mobile   手机号
     * @param string $code   验证码
     * @param string $inviteCode  推荐码
     * @param string $wechat  微信信息
     * @ApiReturn(
    {
    "code": 1,
    "msg": "注册成功",
    "time": "1575516587",
    "data": {
    "userinfo": {
    "id": 7,
    "mobile": "15225140805",
    "username": "15225140805",
    "score": 0,
    "nickname": "15225140805",
    "avatar": "",
    "token": "4708a213-1450-4904-8362-9003069d1c73",
    "user_id": 7,
    "createtime": 1575516587,
    "expiretime": 1578108587,
    "expires_in": 2592000
    }
    }
    }
    )
     */
    public function register()
    {
        header("access-control-allow-headers:*");
        header("access-control-allow-methods:*");
        header("access-control-allow-origin:*");
        $mobile = $this->request->request('mobile');
        $code = $this->request->request('code');
        $inviteCode = $this->request->request('inviteCode');
        $group_id = $this->request->request('group_id',0);
        if (!$mobile) {
            $this->error(__('Invalid parameters'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $wechat = $this->request->request('wechat',"");
        $ret = $this->auth->register($mobile, $mobile, $mobile, $mobile, ['group_id'=>$group_id],$inviteCode,$wechat);
        if ($ret) {
            $data = [
                'userinfo' => $this->auth->getUserinfo(),
                "titleInfo"=>$this->auth->getTitleInfo(),
            ];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }
    /**
     * 发送短信
     * @ApiMethod   (POST)
     * @param string $mobile   手机号
     * @param string $event  类型register注册login登录
     * @ApiReturn(
    {
    "code": 1,
    "msg": "发送成功",
    "time": "1575516526",
    "data": null
    }
    )
     */
    public function send()
    {
        header("access-control-allow-headers:*");
        header("access-control-allow-methods:*");
        header("access-control-allow-origin:*");
        $mobile = $this->request->request("mobile");
        $event = $this->request->request("event");
        $event = $event ? $event : 'register';
        if(!@in_array($event,Sms::getEvent())){
            $this->error(__('Event parameters'));
        }
        if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Incorrect phone number'));
        }
        $last =Sms::get($mobile, $event);
        if ($last && time() - $last['createtime'] < 60) {
            $this->error(__('Frequent transmission'));
        }
//        $ipSendTotal = \app\common\model\Sms::where(['ip' => $this->request->ip()])->whereTime('createtime', '-1 hours')->count();
//        if ($ipSendTotal >= 5) {
//            $this->error(__('Frequent transmission'));
//        }
        $userinfo = User::getByMobile($mobile);
        if (@in_array($event,array('register','update')) && $userinfo) {
            //已被注册
            $this->error(__('Has been registered'));
        }elseif(in_array($event,array('forget','login')) && empty($userinfo)){
            //账号不存在
            $this->error(__('User does not exist'));
        }
        $ret = Sms::send($mobile, null, $event);
        if (\fast\Utils::is_error($ret)) {
            $this->success(__('Send successfully'));
        } else {
            $this->error(__('Sending failed').$ret['message']);
        }
    }
    /**
     * 注销登录
     * @ApiMethod   (POST)
     * @ApiReturn(
    {
    "code": 1,
    "msg": "注销成功",
    "time": "1575516329",
    "data": null
    }
    )
     */
    public function logout()
    {
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }
    /**
     * 登陆初始化
     *
     * @ApiReturn(
    {
    "code": 1,
    "msg": "登陆信息",
    "time": "1575516240",
    "data": {
    "title": "陀螺世界",
    "logo": "http://fastadmin.www.com/uploads/20191130/29a59dc4ad36c1c9080c366082839e81.png",
    "mobileloginstatus": "1",
    "mobileregstatus": "1",
    "wechatloginstatus": "1",
    }
    }
    )
     */
    public function init()
    {
        $data = [
            "title"=>\think\config::get("site.name"),
            "logo"=>\fast\Utils::toMedia(\think\config::get('site.sitelogo')),
            "percent"=>\think\config::get("site.pinggoodspercent"),
            "wechatloginstatus"=>\think\config::get("site.wechatloginstatus"),
            "bdsqurl"=>\think\config::get("site.bdsqurl"),
        ];
        $this->success(__('Login info'), $data);
    }
    /**
     * 协议信息
     * @ApiMethod   (POST)
     * @param string $type   类型1用户协议2隐私协议3上架协议4邀请规则5提现规则6代理7任务赚8回购9团队
     */
    public function agreement()
    {
        header("access-control-allow-headers:*");
        header("access-control-allow-methods:*");
        header("access-control-allow-origin:*");

        $type = $this->request->request("type");
        if($type == 1){
            $title = "用户协议";
            $info = htmlspecialchars_decode(\think\config::get("site.agreementuser"));
        }elseif($type == 2){
            $title = "隐私协议";
            $info = htmlspecialchars_decode(\think\config::get("site.agreementpolicy"));
        }elseif($type == 3){
            $title = "上架协议";
            $info = htmlspecialchars_decode(\think\config::get("site.agreementshelf"));
        }elseif($type == 4){
            $title = "邀请规则";
            $info = htmlspecialchars_decode(\think\config::get("site.agreementinviterules"));
        }elseif($type == 5){
            $title = "提现规则";
            $info = htmlspecialchars_decode(\think\config::get("site.agreementwithdraw"));
        }elseif($type == 6){
            $title = "代理规则";
            $info = htmlspecialchars_decode(\think\config::get("site.agreementagent"));
        }elseif($type == 7){
            $title = "任务赚规则";
            $info = htmlspecialchars_decode(\think\config::get("site.agreementtask"));
        }elseif($type == 8){
            $title = "回购规则";
            $info = htmlspecialchars_decode(\think\config::get("site.agreementback"));
        }elseif($type == 9){
            $title = "团队规则";
            $info = htmlspecialchars_decode(\think\config::get("site.agreementteam"));
        }
        elseif($type == 10){
            $title = "话费充值规则";
            $info = htmlspecialchars_decode(\think\config::get("site.MobileChargeRule"));
        }elseif($type == 11){
            $title = "拼购规则";
            $info = htmlspecialchars_decode(\think\config::get("site.tuangouRule"));
        }elseif($type == 12){
            $title = "板块说明";
            $info = htmlspecialchars_decode(\think\config::get("site.tuangouDesc"));
        }
        $data = [
            "title"=>$title,
            "info"=>$info,
        ];
        $this->success(__('Agreement info'), $data);
    }
    /**
     * 网页注册页面
     * @ApiMethod   (POST)
     * @param string $inviteCode  用户页面inviteCode
     */
    public function download()
    {
        header("access-control-allow-headers:*");
        header("access-control-allow-methods:*");
        header("access-control-allow-origin:*");
        $inviteCode = $this->request->request("inviteCode");
        if(empty($inviteCode)){
            //$this->error(__('Failed to get invitation code'));
        }
        $inviteCode = base64_decode($inviteCode);
        $user = new \app\common\model\User();
        $userInfo = $user->where("invite_code",$inviteCode)->find();
        if(empty($userInfo)){
            //$this->error(__('Failed to get user information'));
        }
        $data = array(
            "title"=>\think\config::get("site.name"),
            "inviteCode"=>$inviteCode,
            "androidurl"=>\think\config::get("site.androidurl"),
            "iosurl"=>\think\config::get("site.iosurl"),
            "logo"=>\fast\Utils::toMedia(\think\config::get('site.sitelogo')),
        );
        $this->success(__("Download information obtained successfully"),$data);
    }
    /**
     * 检查更新
     * @ApiMethod   (POST)
     * @param  string version   版本号
     * @param string type 类型 android安卓 ios苹果
     * @ApiReturn(
    {
    "code": 1,
    "msg": "版本更新信息",
    "time": "1575704640",
    "data": {
    "version": "0.0.99",
    "type": "ios",
    "new_version": "1.0.0",
    "url": "http://fastadmin.www.com/hotcode/ios/1.0.0/update.wgt",
    "types": "1",
    "update": "0"
    }
    }
    )
     */
    public function checkUpdate()
    {
        //传过来的版本
        $version = $this->request->request('version');
        $type = $this->request->request('deviceType',$this->request->request('type',""));
        $systemVersion = \think\config::get('site.'.$type.'version');
        $url = \think\config::get('site.'.$type.'url');
        $types = \think\config::get('site.'.$type.'type');
        $update = \think\config::get('site.'.$type.'update');
        if($types == 1){
            $url = \think\config::get("site.aliyundomain").'/hotcode/' . $type . '/' . $systemVersion . '/widget.zip';
        }
        $data = [
            "version"=>$version,
            'type'=>$type,
            'new_version'=>$systemVersion,
            'url'=>!empty($url)?$url:"",
            'types'=>$types,
            "update"=>$update
        ];
        if (version_compare($version, $systemVersion, '>=')) {
            $data["url"] = "";
            $this->success(__('It\'s the latest version'),$data);
        }
        $this->success(__('Version update information'),$data);
    }
    /**
     * 二维码信息
     * @ApiInternal
     */
    public function qrcode()
    {
        $qrcodeUrl = base64_decode($this->request->request("code"));
        if(empty($qrcodeUrl)){
            $this->error("参数异常");
        }
        $qrCode = new \Endroid\QrCode\QrCode($qrcodeUrl);
        $qrCode->setSize(150);
        $qrCode->setMargin(10);
        echo $qrCode->writeString();
        exit;
    }
    /**
     * 唤醒跳转网页端
     */
    public function wakeUp()
    {

        header("Content-type:application/pdf");
        header("Content-Disposition:attachment;filename='http://shoubeikeji.com/1.2.3.apk'");
        exit;
        $url = $this->request->request('url');
        if($this->IsWeiXinApp()){
            if($this->isQq()){
            }
        }
        header("location:" . $url);    //在浏览器展示下载落地页
        exit;
    }
    public function isWeiXinApp()
    {
        $Headers = $this->request->getHeaders();
        $user_agent = $Headers->get('user-agent');
        if (strpos($user_agent, 'MicroMessenger') === false) {
            return false;
        } else {
            if (strpos($user_agent, "wechatdevtools")) {
                return false;
            }
            if (strpos($_SERVER['HTTP_USER_AGENT'], 'Android')) {
                return true;
            }
        }
        return false;

    }
    public function isQq()
    {
        $Headers = $this->request->get("user-agent");
        $user_agent = $Headers->get('user-agent');
        if (strpos($user_agent, "MQQBrowser")) {
            if (strpos($_SERVER['HTTP_USER_AGENT'], 'Android')) {
                return true;
            }
        }
        return false;
    }
    /**
     * 测试
     */
    public function ceshiSms()
    {
        $url = \app\common\library\Shorturl::create("https://fanyi.baidu.com/#en/zh/recover");
        var_dump($url);
        $text = \app\common\library\Shorturl::recover($url);
        var_dump($text);
        exit;
        Sms::otherSend([
            "uid"=>299,
            "type"=>8,
            "level"=>2,
            "price"=>"2",
        ]);
        Sms::otherSend([
            "uid"=>299,
            "type"=>7,
            "mobile"=>"1234",
            "price"=>"2",
        ]);
        exit;
        Sms::otherSend([
            "uid"=>299,
            "type"=>6,
            "orderId"=>"pt123123123",
            "chaPrice"=>"120",
            "countPrice"=>"220",
        ]);
       /* Sms::otherSend([
            "uid"=>186,
            "type"=>5,
            "price"=>"2",
        ]);*/
        /*Sms::otherSend([
            "uid"=>186,
            "type"=>4,
            "orderId"=>"pt200913150500001",
            "payPrice"=>10,
        ]);*/
        Sms::otherSend([
            "uid"=>299,
            "type"=>3,
            "level"=>1,
            "mobile"=>"1234",
            "payPrice"=>"11",
            "title"=>"一级代理",
            "price"=>2,
        ]);
        Sms::otherSend([
            "uid"=>299,
            "type"=>2,
            "payPrice"=>"2",
            "backPrice"=>"1",
        ]);
        exit;
        /*Sms::otherSend([
            "uid"=>186,
            "type"=>1,
            "orderId"=>"pt200913150500001",
        ]);*/
        exit;

        Sms::sendMsg("18749320615","您的订单已经开始发货，订单商品有（苹果11，小米电视  #name#），快递会尽快送达。");
        Sms::sendMsg("18749320615","恭喜！您的订单已经回购成功，订单金额1000 #number#元，回购到账1000#number1#元，请打开app查看账户余额详情。");
        Sms::sendMsg("18749320615","您的二级团队成员尾号9658  #number# ，缴费1000 #number1#元成功升级为二级代理，您获得团队成员升级奖励1000 #number2#元，已经到账，请打开app查看账户余额详情。");
        Sms::sendMsg("18749320615","您于2020-9-7 17:06:44   #time#参与拼单购买商品苹果手机11  #name#，已成功使用余额抵扣300 #number# 元  ，请打开app查看账户余额详情。");
        Sms::sendMsg("18749320615","您于2020-9-7 17:07:57  #time# 手动提现1000  #number# 元到支付宝，系统已打款成功，请及时查收。");
        Sms::sendMsg("18749320615","您的订单****  #number# ,还差1000  #number1# 元完成拼团,请邀请好友购买任意商品累积金额达到1000  #number2#元即可发货，完成团购还能领取现金奖励!");
        Sms::sendMsg("18749320615","您邀请的好友尾号7769 #number# 已参与拼单，您获得任务赚奖励200 #number1#元，已经到账，请打开app查看账户余额详情。");
        Sms::sendMsg("18749320615","您的三 #number#级团员成功付费参与拼单，您获得团队奖励25 #number1#元，已经到账，请打开app查看账户余额详情。");
        exit;
    }

}
